package com.crm.dataReceive.controller;

import com.alibaba.fastjson2.JSONObject;
import com.crm.custinfo.domain.CustCommentRecord;
import com.crm.custinfo.domain.CustInfo;
import com.crm.custinfo.domain.HitPackage;
import com.crm.custinfo.service.ICustCommentRecordService;
import com.crm.custinfo.service.ICustInfoService;
import com.crm.custinfo.service.IHitPackageService;
import com.crm.dataReceive.domain.CheckApi;
import com.crm.dataReceive.domain.Customer;
import com.crm.dataReceive.domain.LittleWeiReq;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.utils.AesUtils;
import com.ruoyi.common.utils.Md5Encrypt;
import com.ruoyi.common.utils.ObjectUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/qd")
public class QdController {
    public static final org.slf4j.Logger logger = LoggerFactory.getLogger("CustPrefix8CheckInfo");
    @Autowired
    private IHitPackageService hitPackageService;
    private final static String AES_KEY = "P4ewnDAWzaBUYfwG";
    @Autowired
    private ICustInfoService custInfoService;
    @Autowired
    private ICustCommentRecordService custCommentRecordService;
    @Anonymous
    @PostMapping("/check/tenant/{tenantId}")
    public Map<String, Object> check(@RequestBody CheckApi checkApi) {
        Map<String, Object> map = new HashMap<>();
        try {
            if (checkApi == null) {
                map.put("code", 500);
                map.put("msg", "请求包数据为空");
                map.put("data",new String[]{});
                return map;
            }
            String data = checkApi.getData();
            try {
                data= AesUtils.decryptPKCS5Padding(data, AES_KEY);
            }catch (Exception e) {
                map.put("code", 500);
                map.put("msg", "解密失败");
                map.put("data",new String[]{});
                logger.error("小薇撞库解密失败[{}]", e.getMessage());
                return map;
            }
            JSONObject jsonObject = JSONObject.parseObject(data);
            String encryptValue = jsonObject.getString("phone");
            String city = jsonObject.getString("city");
            city = city == null ? "" : city.replace("市", "").replace("地区", "");
            String mobileMd5 = Md5Encrypt.md5(encryptValue);
            if (StringUtils.isBlank(mobileMd5)) {

                map.put("code", 500);
                map.put("msg", "解密失败");
                map.put("data",new String[]{});
                return map;
            }
            HitPackage hitPackage = new HitPackage();
            hitPackage.setMobilePrefix8Md5(Md5Encrypt.md5(encryptValue.substring(0,8)));
            List<HitPackage> custs= hitPackageService.selectHitPackageList(hitPackage);
            if (CollectionUtils.isNotEmpty(custs)) {
                String[] data2= new String[custs.size()];
                for (int i = 0; i < custs.size(); i++) {
                    data2[i] = custs.get(i).getMobileMd5();
                }
                map.put("code", 200);
                map.put("msg", "操作成功");
                map.put("data",data2);

                return map;
            }
            map.put("code", 200);
            map.put("msg", "操作成功");
            map.put("data",new String[]{});
            return map;
        } catch (Exception e) {
            map.put("code", 500);
            map.put("msg", "撞库失败");
            map.put("data",new String[]{});
            logger.error("小薇撞库失败[{}]", e.getMessage());
            return map;
        }
    }
    @Anonymous
    @PostMapping("/apply/tenant/{tenantId}")
    public Map<String, Object> apply(@RequestBody LittleWeiReq littleWeiReq) {
        Map<String, Object> map = new HashMap<>();
        try {
            String realRequestData = "";
            try {
                realRequestData = AesUtils.decryptPKCS5Padding(littleWeiReq.getData(), AES_KEY);
            } catch (Exception e) {
                logger.error("小薇进件解密异常[{}]", e.getMessage());
                map.put("code", 500);
                map.put("msg", "解密失败");
                return map;
            }
            JSONObject jsonObject = JSONObject.parseObject(realRequestData);
            LittleWeiReq applyInfo = jsonObject.toJavaObject(LittleWeiReq.class);
            Customer customer = new Customer();
            customer.setMobile(applyInfo.getPhone());
            customer.setCustName(applyInfo.getName());
            String mobile = customer.getMobile();
            String md5value = Md5Encrypt.md5(customer.getMobile());
            int count = custInfoService.countByMd5(md5value);
            if (count > 0 ) {
                map.put("code", 500);
                map.put("msg", "撞库未通过");
                return map;
            }
            String city = applyInfo.getCity();
            city = city == null ? "" : city.replace("市", "").replace("地区", "");
            customer.setCity(city);
            int loanAmount = 0;
            if (applyInfo.getLoanAmount() == 1) {
                loanAmount = 30000;
            } else if (applyInfo.getLoanAmount() == 2) {
                loanAmount = 50000;
            } else if (applyInfo.getLoanAmount() == 3) {
                loanAmount = 100000;
            }
            customer.setApplyLimit(new BigDecimal(loanAmount));
            customer.setSex(StringUtils.defaultIfBlank(String.valueOf(applyInfo.getGender()), "0"));
            customer.setAge(applyInfo.getAge() == null ? 0L : applyInfo.getAge());// 年龄
            customer.setChannelSource(littleWeiReq.getBusinessCode());

            CustInfo custInfo = new CustInfo();
            ObjectUtil.copyProperties(customer, custInfo);

            custInfo.setRepeatFlag("0");
            if (custInfo.getApplyTime() == null) {
                custInfo.setApplyTime(new Date());
            }
            custInfo.setMd5val(md5value);
            if(applyInfo.getProvidentFund()==4){
                custInfo.setHasFund("0");
            }else{
                custInfo.setHasFund("1");
            }
            if(applyInfo.getSocialSecurity()==4){
                custInfo.setHasSocial("0");
            }else{
                custInfo.setHasSocial("1");
            }
            if(applyInfo.getHouse()==1){
                custInfo.setHasHouse("1");
            }else{
                custInfo.setHasHouse("0");
            }
            if(applyInfo.getVehicle()==1){
                custInfo.setHasCar("1");
            }else{
                custInfo.setHasCar("0");
            }
            // 分发系统唯一id
            custInfo.setDistributeId(-1L);
            logger.info("线索接收API请求转换：{}", custInfo.toString());
            // 客户申请信息前置检查
            Map<String, Object> checkResult = custInfoService.checkCustInfo(custInfo, logger);
            if (MapUtils.getIntValue(checkResult, "errorNo", -1) != 0) {
                map.put("code", 500);
                map.put("msg", MapUtils.getString(checkResult, "errorInfo", ""));
                return map;
            }
            // 随机分配
            Long[] orgIds = custInfoService.getOrgIdsByCity(custInfo.getCity());
            boolean isSucceed = custInfoService.dealCustRandomly(custInfo, orgIds, true, false, logger);
            if (isSucceed) {
                map.put("code", 200);
                map.put("msg", "线索接收成功");
                if (StringUtils.isNotBlank(custInfo.getRemark())) {
                    // 自动生成一条备注
                    CustCommentRecord record = new CustCommentRecord();
                    record.setCustId(custInfo.getId());
                    record.setEmpId(null);
                    record.setEmpName("系统自动备注");
                    record.setRemark(custInfo.getRemark());
                    record.setType(1L);
                    record.setType2(1L);
                    record.setCreateTime(new Date());
                    custCommentRecordService.insertCustCommentRecord(record);
                }
            } else {

                map.put("code", 500);
                map.put("msg", "线索接收API请求申请异常");
                logger.error("小薇进件申请失败[{}]", custInfo.toString());
                return map;
            }
            map.put("code", 200);
            map.put("msg", "线索接收成功");
        } catch (Exception e) {
            logger.error("小薇进件申请失败[{}]", e.getMessage());
        }
        return map;
    }
}
